﻿/***************************************************************************************************
 * Filename:            Function.cs
 * Module:              一些常用的函数
 * Copyright:           2008 穗联软件 版权所有
 * Author:              吴潮槟
 * Created Date:        2008-11-16
 * Last Modified Data:  
 * Description:         
***************************************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace GCELibrary.Current
{
    public static class Function
    {

        public static string MaxLength(this string value,int length)
        {
            string result=null;
            if (value != null)
            {
                if (value.Length > length)
                    result = value.Substring(0, length);
                else
                    result = value;
            }
            return result;
        }

        /// <summary>
        /// 将一个数据集按分隔符分隔组合成一个字符串,
        /// </summary>
        /// <param name="valueArr">整型数组</param>
        /// <param name="splitKey">分隔符</param>
        /// <returns></returns>
        public static string ConstituteString(this IEnumerable items, string splitKey)
        {
            string result = "";
            
            if (items == null) return result;

            foreach (object item in items)
            {
                if (string.IsNullOrEmpty(result))
                {
                    result = item.ToString();
                }
                else
                {
                    result += splitKey + item.ToString();
                }
            }
            return result;
        }
        /// <summary>
        /// 将一个数据集按逗号分隔组合成一个字符串
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static string ConstituteString(this IEnumerable items) 
        {
            return ConstituteString(items, ",");
            
        }

        /// <summary>
        /// 忽略大小写，返回字符串是否相等
        /// </summary>
        /// <param name="source"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool EqIgnoreCase(this string source, string value)
        {
            return source.Equals(value, StringComparison.OrdinalIgnoreCase);
        }

        #region 空值处理

        /// <summary>
        /// 如果value为空字符串或字符串长度为0则返回null
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string EmptyString(this string value)
        {
            return EmptyString(value, null);
        }
        /// <summary>
        /// 如果value为空字符串或字符串长度为0则返回def
        /// </summary>
        /// <param name="value"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public static string EmptyString(this string value, string def)
        {
            if (value != null)
            {
                if (value.Trim() == "")
                    return def;
                else
                    return value;
            }
            else
                return def;
        }
        /// <summary>
        /// 如果value为空字符串或字符串长度为0则返回null
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int? EmptyInt(this string value)
        {
            if (EmptyString(value) == null)
                return null;
            else
                return value.Convert<int>();
        }
        /// <summary>
        /// 如果value为空字符串或字符串长度为0则返回def
        /// </summary>
        /// <param name="value"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public static int EmptyInt(this string value, int def)
        {
            if (EmptyString(value) == null)
                return def;
            else
                return value.Convert<int>();
        }
        /// <summary>
        /// 如果value为空字符串或字符串长度为0则返回null
        /// </summary>
        /// <param name="value"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public static DateTime? EmptyDateTime(this string value)
        {
            if (EmptyString(value) == null)
                return null;
            else
                return value.Convert<DateTime>();

        }
        /// <summary>
        /// 如果value为空字符串或字符串长度为0则返回def
        /// </summary>
        /// <param name="value"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public static DateTime EmptyDateTime(this string value, DateTime def)
        {
            if (EmptyString(value) == null)
                return def;
            else
                return value.Convert<DateTime>();
        }

        #endregion

        #region 类型转换

        /// <summary>
        /// 转换指定格式，如果出现错误则抛出异常
        /// </summary>
        /// <typeparam name="T">要转换的数据类型</typeparam>
        /// <param name="value">转换的值</param>
        /// <returns></returns>
        public static T Convert<T>(this object value)
        {
            return Convert<T>(value, true);
        }
        /// <summary>
        /// 转换指定格式，如果出现错误则抛出异常
        /// </summary>
        /// <typeparam name="T">要转换的数据类型</typeparam>
        /// <param name="value">转换的值</param>
        /// <returns></returns>
        public static T Convert<T>(this object value, T def)
        {
            if (value == null)
                return def;
            value.Convert<T>(out def);
            return def;
        }

        /// <summary>
        /// 转换指定格式
        /// </summary>
        /// <typeparam name="T">要转换的数据类型</typeparam>
        /// <param name="Value">转换的值</param>
        /// <param name="ShowError">如果出现错误是否抛出异常</param>
        /// <returns></returns>
        public static T Convert<T>(this object value, bool showError)
        {
            Exception ex = null;
            T t = default(T);
            bool isSuccess = Convert<T>(value, out t, out ex);
            if (!isSuccess && showError)
            {
                throw ex;
            }
            else
            {
                return t;
            }
        }
        /// <summary>
        /// 转换指定格式
        /// </summary>
        /// <typeparam name="T">要转换的数据类型</typeparam>
        /// <param name="Value">转换的值</param>
        /// <param name="OutValue">转换输出的值</param>
        /// <returns>结果true正常，false引发异常</returns>
        public static bool Convert<T>(this object value, out T outValue)
        {
            Exception ex = null;
            return Convert<T>(value, out outValue, out ex);
        }
        /// <summary>
        /// 转换指定格式
        /// </summary>
        /// <typeparam name="T">要转换的数据类型</typeparam>
        /// <param name="value">转换的值</param>
        /// <param name="message">转换不成功提示信息</param>
        /// <returns></returns>
        public static T Convert<T>(this object value, string message)
        {
            var t = default(T);
            try
            {
                t = Convert<T>(value);
            }
            catch
            {
                throw new ArgumentException(message);
            }
            return t;
        }

        /// <summary>
        /// 转换指定格式
        /// </summary>
        /// <typeparam name="T">要转换的数据类型</typeparam>
        /// <param name="Value">转换的值</param>
        /// <param name="OutValue">转换输出的值</param>
        /// <param name="ex">引发的异常</param>
        /// <returns>结果true正常，false引发异常</returns>
        private static bool Convert<T>(this object value, out T outValue, out Exception ex)
        {
            bool result = false;
            ex = null;
            try
            {
                var type = typeof(T);
                if (type.IsEnum)
                {
                    outValue = (T)Enum.Parse(typeof(T), value.ToString());
                }
                else
                {
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        type = Nullable.GetUnderlyingType(type);
                        if (value == null || string.IsNullOrEmpty(string.Concat(value)))
                        {
                            outValue = default(T);
                            return true;
                        }
                        
                    }
                    outValue = (T)System.Convert.ChangeType(value, type);
                }
                result = true;
            }
            catch (Exception e)
            {
                ex = new Exception(string.Format("转换类型出错,值“{0}”无法转换成“{1}”类型", value==null?"Null":value.ToString(), typeof(T).ToString()), e);
                outValue = default(T);
            }
            return result;
        }
        /// <summary>
        /// 转换指定格式，如果出现错误则抛出异常
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T Convert<T>(this string value)
        {
            return Convert<T>((object)value);
        }
        /// <summary>
        /// 转换数据集元素的类型
        /// </summary>
        /// <typeparam name="T">要转换成的元素类型</typeparam>
        /// <param name="Collection"></param>
        /// <returns></returns>
        public static T[] Convert<T>(this Array Collection)
        {
            List<T> list = new List<T>();
            foreach (var item in Collection)
            {
                list.Add(item.Convert<T>());
            }
            return list.ToArray();
        }
        /// <summary>
        /// 交换数据集，从一个数据集类型转换为另一个数据集类型,转换后的类型必须可实例化
        /// </summary>
        /// <typeparam name="T">转换后的类型</typeparam>
        /// <typeparam name="U">数据集的类型</typeparam>
        /// <param name="items">数据，必须实现IEnumerable(of T)接口</param>
        /// <returns></returns>
        public static T Convert<T, U>(this IEnumerable<U> items) where T : ICollection<U>, new()
        {
            T t = new T();
            foreach (U item in items)
            {
                var type = item.GetType();
                var cc = type.GetProperties();
                t.Add(item);
            }
            return t;
        }

        #endregion
        /// <summary>
        /// 返回枚举类型字段的注释名称，以及字段名称，key=注释名称
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IList<KeyValuePair<object, string>> GetEnumFieldsDescription(this Type type)
        {
            if (!type.IsEnum)
                throw new ArgumentNullException("参数类型必须为枚举类型");
            var names = Enum.GetNames(type);
            IList<KeyValuePair<object, string>> result = new List<KeyValuePair<object, string>>();
            foreach (var name in names)
            {
                var en = Enum.Parse(type, name);
                var des = DescriptionAttribute.GetEnumDescription(en);
                if (des != null)
                {
                    result.Add(new KeyValuePair<object,string>(en, des.Name));
                }
            }
            return result.ToArray();
        }

        #region Json序列化
        public static string JsonConvert(this object o)
        {
          return  Newtonsoft.Json.JsonConvert.SerializeObject(o);
        }
        public static T JsonConvert<T>(this string str)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
        }
        #endregion
    }
  
}
